package cn.rkylin.oms.sysOrder.service;

import cn.rkylin.apollo.common.util.HttpUtils;
import cn.rkylin.core.utils.SnoGerUtil;
import cn.rkylin.oms.common.dto.DBLog;
import cn.rkylin.oms.common.utils.LogUtil;
import cn.rkylin.oms.sysOrder.dao.ISysOrderDAO;
import cn.rkylin.oms.sysOrder.domain.SysOrderGoods;
import cn.rkylin.oms.sysOrder.vo.SysOrderVO;
import cn.rkylin.oms.system.shop.vo.ShopVO;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统订单促销上赠品
 *
 * @author wangxing
 * @version 1.0
 * @created 2017.09.14
 */
@Service("sysOrderPromotionRuleService")
public class SysOrderPromotionRuleService {

    //待上促销规则的系统订单数据集
//    private List<SysOrderVO> sysOrderAllList = null;
    //系统订单商品与系统订单关联关系map
//    private Map<String, List<SysOrderGoods>> sysOrderGoodsMap = null;

    @Autowired
    private ISysOrderDAO sysOrderDAO;

    /**
     * OMS调用地址
     */
    @Value("${oms.address}")
    private String omsUrl;

    /**
     * 日志类
     */
    @Autowired
    private LogUtil logUtil;

    /**
     * 系统订单促销上赠品
     *
     * @param shopVO
     * @param buyerNick 家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @throws Exception
     */
    public void sysOrderPromotionRule(ShopVO shopVO, String buyerNick, String tradeCode) throws Exception {
        //店铺id
        String strShopId = shopVO.getShopId();
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单促销上赠品开始---------------------------------------"));
        //待上促销规则的系统订单数据集
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        //系统订单商品与系统订单关联关系map
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();

//1.1、获取待上促销规则的系统订单数据集------------------------------------------------------------------------------------------
        Map<String, Object> orderIdAddMap = new HashMap();
        sysOrderAllList = getSysOrderList(strShopId, buyerNick, tradeCode, orderIdAddMap);
        if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取促销待上赠品系统订单数为:" + String.valueOf(sysOrderAllList.size())));
//1.2、获取系统订单商品数据集，并映射Map关系------------------------------------------------------------------------------------------
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取待上赠品系统订单商品开始"));
            sysOrderGoodsMap = getSysOrderGoodsMap(orderIdAddMap);
            if (sysOrderGoodsMap != null && sysOrderGoodsMap.size() > 0) {
                String strOrderId = "";//订单Id
                SysOrderVO sysOrderVO = new SysOrderVO();//订单实体
                List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();//订单对应商品明细
//                List<SysOrderGoods> sysOrderGoodsGiftList = new ArrayList<SysOrderGoods>();//订单按促销规则待上的赠品列表
//1.3、开始逐条循环订单调用促销规则获取赠品信息------------------------------------------------------------------------------------------
                // 请求地址
                String requestUrl = omsUrl + "salesPromotion/getRuleByOrderVO.action";
                // 请求参数拼接
                String requestParams = "";
                // 请求数据
                String resJson = "";
                // 转换响应数据
                Map<String, Object> resultMap = null;
                //循环系统订单
                for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                    List<SysOrderGoods> sysOrderGoodsGiftList = new ArrayList<SysOrderGoods>();//订单按促销规则待上的赠品列表
                    sysOrderVO = sysOrderAllList.get(orderIndex);
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号:" + sysOrderVO.getOrderCode() + "促销上赠品开始*******************"));
                    strOrderId = sysOrderVO.getOrderId();
                    sysOrderGoodsList = sysOrderGoodsMap.get(strOrderId);//当前订单对应商品明细
                    if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0) {
                        sysOrderVO.setSysOrderGoodsList(sysOrderGoodsList);
                    }
//调用OMS 促销规则Controller 返回当前系统订单数据集中满足促销规则需要上的赠品数据 入参：sysOrderVO;出参：返回SysOrderGoods实体的List
                    try {
                        // 请求参数拼接
                        requestParams = JSON.toJSONString(sysOrderVO);
                        // 请求数据
                        resJson = HttpUtils.sendByPostJson(requestUrl, requestParams);
                        // 转换响应数据
                        resultMap = JSON.parseObject(resJson, Map.class);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        resultMap = null;
                    }
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号:" + sysOrderVO.getOrderCode() + "获取促销待上赠品信息阶段结束*******************"));
                    if (resultMap != null && resultMap.size() > 0) {
                        if (resultMap.containsKey("result")
                                && "success".equals(resultMap.get("result"))) {
//                            sysOrderGoodsGiftList = JSON.parseArray(resultMap.get("data").toString(), SysOrderGoods.class);
                            Map<String, Object> dataMap = JSON.parseObject(resultMap.get("data").toString(), Map.class);
                            if (dataMap != null) {
                                for (Map.Entry<String, Object> entry : dataMap.entrySet()) {
                                    if (entry.getValue() != null) {
                                        SysOrderGoods SysOrderGoodsGift = JSON.parseObject(entry.getValue().toString(), SysOrderGoods.class);
                                        SysOrderGoodsGift.setOrderGoodsId(SnoGerUtil.getUUID());
                                        SysOrderGoodsGift.setOrderId(strOrderId);
                                        SysOrderGoodsGift.setIsGift("y");
                                        SysOrderGoodsGift.setTradeCode(sysOrderVO.getTradeCode());
                                        SysOrderGoodsGift.setQty(SysOrderGoodsGift.getSendCount());
                                        sysOrderGoodsGiftList.add(SysOrderGoodsGift);
                                    }
                                }
                            }
                        }
                    }
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号:" + sysOrderVO.getOrderCode() + "赠品赋值阶段结束*******************"));
//1.4、开始插入订单对应的赠品信息到数据库-----------------------------------------------------------------------------------
                    //插入赠品信息到数据库
                    if (sysOrderGoodsGiftList != null && sysOrderGoodsGiftList.size() > 0) {
                        insertSysOrderGiftInfo(strOrderId, sysOrderVO.getOrderCode(), sysOrderGoodsGiftList);
                        logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号:" + sysOrderVO.getOrderCode() + "赠品插入数据库阶段结束,赠品数:" + String.valueOf(sysOrderGoodsGiftList.size())));
                    }
//1.5、开始逐条更新订单进系统上促销步骤状态 p -----------------------------------------------------------------------------------
                    updateSysOrderStatus(strOrderId, sysOrderVO.getOrderCode());
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "更新促销上赠品阶段状态处理结束*******************"));
                    logUtil.info(new DBLog(sysOrderVO.getOrderCode(), "系统订单自动下载", "跟踪日志", "订单编号" + sysOrderVO.getOrderCode() + "促销上赠品结束*******************"));
                }
            }
        } else {
            logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取促销待上赠品系统订单数为:0"));
        }
        logUtil.info(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "shopAccount:" + shopVO.getShopAccount() + " 系统订单促销上赠品结束---------------------------------------"));
    }

    /**
     * 获取待上促销规则的系统订单数据集，并返回订单id累加数据集Map
     *
     * @param strShopId
     * @param buyerNick 买家昵称 客户ID（手动下载用）
     * @param tradeCode 平台交易号（手动下载用）
     * @return
     * @throws Exception
     */
    private List<SysOrderVO> getSysOrderList(String strShopId, String buyerNick, String tradeCode, Map<String, Object> orderIdAddMap) throws Exception {
//        Map<String, Object> returnMap = null;
        List<SysOrderVO> sysOrderAllList = new ArrayList<SysOrderVO>();
        try {
            //数据库参数
            Map<String, String> sysOrderMap = new HashMap();
            sysOrderMap.put("shopId", strShopId);
            sysOrderMap.put("orderStatus", "a");
            sysOrderMap.put("jobStep", "c");
            sysOrderMap.put("combStus", "w");
            sysOrderMap.put("isCancel", "n");
//        sysOrderMap.put("isLock", "n");
            sysOrderMap.put("operStus", "w");
            if (StringUtils.isNotBlank(tradeCode)) {
                sysOrderMap.put("tradeCode", tradeCode);
            }
            if (StringUtils.isNotBlank(buyerNick)) {
                sysOrderMap.put("buyerNick", buyerNick);
            }
            sysOrderMap.put("limitCout", "");//top count
            //获取待上促销规则的系统订单数据集------------------------------------------------------------------------------------------
            sysOrderAllList = sysOrderDAO.selectSysOrderList(sysOrderMap);
            if (sysOrderAllList != null && sysOrderAllList.size() > 0) {
                //系统订单Id累加拼串，用于获取订单商品信息入参
                List<String> orderIdAddList = new ArrayList<String>();
                for (int orderIndex = 0; orderIndex < sysOrderAllList.size(); orderIndex++) {
                    orderIdAddList.add(sysOrderAllList.get(orderIndex).getOrderId());
                }

                orderIdAddMap.put("order_id", orderIdAddList);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderAllList = null;
            orderIdAddMap = null;
            logUtil.error(new DBLog(strShopId, "系统订单自动下载", "跟踪日志", "获取促销待上赠品系统订单异常:" + ex.getMessage()));
        }
        return sysOrderAllList;
    }

    /**
     * 获取系统订单商品数据集，并映射其与系统订单的Map关系
     *
     * @param map
     * @throws Exception
     */
    private Map<String, List<SysOrderGoods>> getSysOrderGoodsMap(Map<String, Object> map) throws Exception {
        Map<String, List<SysOrderGoods>> sysOrderGoodsMap = new HashMap();
        try {
            if (map != null && map.size() > 0) {
                //获取系统订单商品数据集------------------------------------------------------------------------------------------
                List<SysOrderGoods> sysOrderGoodsAllList = sysOrderDAO.selectSysOrderGoodsList(map);
                if (sysOrderGoodsAllList != null && sysOrderGoodsAllList.size() > 0) {
                    //系统订单商品实体
                    SysOrderGoods sysOrderGoods = new SysOrderGoods();
                    //系统订单id累加，作为主键
                    String strKey = "";
                    //系统订单商品临时列表
                    List<SysOrderGoods> sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                    //循环系统订单 按合并订单条件各自组合Map
                    for (int orderGoodsIndex = 0; orderGoodsIndex < sysOrderGoodsAllList.size(); orderGoodsIndex++) {
                        sysOrderGoods = sysOrderGoodsAllList.get(orderGoodsIndex);
                        strKey = sysOrderGoods.getOrderId();
                        if (sysOrderGoodsMap.get(strKey) != null) {
                            sysOrderGoodsList = sysOrderGoodsMap.get(strKey);
                        } else {
                            sysOrderGoodsList = new ArrayList<SysOrderGoods>();
                        }
                        //累加系统订单商品
                        sysOrderGoodsList.add(sysOrderGoods);
                        sysOrderGoodsMap.put(strKey, sysOrderGoodsList);
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            sysOrderGoodsMap = null;
            logUtil.error(new DBLog("", "系统订单自动下载", "跟踪日志", "获取待上赠品系统订单商品异常:" + ex.getMessage()));
        }

        return sysOrderGoodsMap;
    }

    /**
     * 系统订单赠品插入数据库
     *
     * @param strOrderId
     * @param sysOrderGoodsList
     * @return
     * @throws Exception
     */
    private void insertSysOrderGiftInfo(String strOrderId, String strOrderCode, List<SysOrderGoods> sysOrderGoodsList) throws Exception {
        int iRes = 0;
        try {
            //循环系统订单对应赠品信息
            if (sysOrderGoodsList != null && sysOrderGoodsList.size() > 0) {
                for (int sysOrderGoodsIndex = 0; sysOrderGoodsIndex < sysOrderGoodsList.size(); sysOrderGoodsIndex++) {
                    SysOrderGoods sysOrderGoods = sysOrderGoodsList.get(sysOrderGoodsIndex);
                    //系统订单赠品明细信息插入数据库
                    iRes = sysOrderDAO.insertSelectiveSysOrderGoods(sysOrderGoods);
                    if (iRes > 0) {
                        //记录日志
                        logUtil.info(new DBLog(strOrderCode, "系统订单自动计算促销规则", "系统订单自动计算促销规则", "系统订单自动计算促销规则上赠品成功 规格商家编码为：" + sysOrderGoods.getSkuCode()));
                    }
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            logUtil.error(new DBLog(strOrderCode, "系统订单自动下载", "跟踪日志", "赠品插入数据库阶段异常:" + ex.getMessage()));
        }
    }


    /**
     * 更新订单进系统上促销步骤状态
     *
     * @param strOrderId
     * @param strOrderCode
     * @return
     * @throws Exception
     */
    private int updateSysOrderStatus(String strOrderId, String strOrderCode) throws Exception {
        int iRes = 0;
        try {
            if (StringUtils.isNotBlank(strOrderId)) {
                SysOrderVO sysOrder = new SysOrderVO();
                sysOrder.setOrderId(strOrderId);
                sysOrder.setJobStep("p");
                iRes = sysOrderDAO.updateByPrimaryKeySelectiveSysOrder(sysOrder);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            iRes = 0;
            logUtil.error(new DBLog(strOrderCode, "系统订单自动下载", "跟踪日志", "更新促销上赠品阶段状态处理异常:" + ex.getMessage()));
        }
        return iRes;
    }

}
